import { updataUserInfo, checkTxt } from '@/api/user.js';
import Vue from 'vue'
// 更新用户信息
export function updateUserInfoFn(params) {
	return new Promise((resolve, reject) => {
		if (params.id) {
			updataUserInfo(params).then(result => {
				if (result && result.code === 200) {
					// console.log(result);
					Vue.prototype.$store.dispatch('setLoginStatus', true);
					resolve(result);
				} else {
					reject();
				}
			})
		}
	})
}

// 展示用户详情
export function getUserInfo() {
	const that = this;
	// #ifdef MP-QQ
	uni.getUserInfo({
		success(result) {
			const userInfo = result.userInfo;
			// console.log(userInfo)
			if (userInfo) {
				updateUserInfoFn({
					avatar: userInfo.avatarUrl,
					address: `${userInfo.country}${userInfo.province}${userInfo.city}`,
					nickname: userInfo.nickName,
					id: Vue.prototype.$store.state.userInfo.id,
					gender: userInfo.gender
				});
			}
		}
	})
	// #endif
}

// 订阅消息
export function subscribeMessage(subscribeMessageId) {
	const that = this;
	return new Promise((resolve, reject) => {
		if (subscribeMessageId) {
			uni.requestSubscribeMessage({
				tmplIds: subscribeMessageId,
				success (res) {
					resolve();
				},
				fail (res) {
          console.log(res);
					reject();
				}
			})
		} else {
			resolve();
		}
	})
}

// 解析url参数
export function parseQueryString(str) {
	let params = {};
  let arr = str;
  if (arr.length <= 1) {
    return params;
  }
  arr = arr.split('&');
  for (let i = 0, l = arr.length; i < l; i++) {
    let a = arr[i].split('=');
    params[a[0]] = a[1];
  }
  return params;
}

// 检查文字
export async function checkText(text) {
  return new Promise(async (resolve, reject) => {
		let flag = true;
    await checkTxt({
      text
    }).then(result => {
      if (result && result.data) {
        flag = true;
      } else {
        flag = false;
      }
    }).catch(() => {
      flag = false;
    })
		resolve(flag);
  })
}

// 获取文件对象
export function dataURLtoFile(dataurl, filename) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	let fileType = mime.split('/');
	return new File([u8arr], `${filename}${fileType.length > 1 ? '.' + fileType[1] : ''}`, { type: mime });
}

export function commonUploadFile(filePath, uploadUrl, formData) {
	let businessId = '';
	// #ifdef MP
	businessId = config.id;
	// #endif
	// #ifdef H5
	businessId = uni.getStorageSync('businessId');
	// #endif
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: uploadUrl,
			filePath,
			name: 'file',
			formData,
			header: {
				businessId: businessId
			},
			success: (imgRes) => {
				uni.hideLoading();
				let result = JSON.parse(imgRes.data)
				if (result.code == 200 && result.data) {
					resolve(result.data);
				} else {
					uni.showToast({
						icon: 'none',
						title: '上传失败，请重试'
					});
					reject('');
				}
			},
			fail: function(e) {
				reject('');
				console.log(e);
			}
		});
	})
}

